//
//  AWUserAccountViewModel.swift
//  WeiBo
//
//  Created by AaronWei on 2017/6/7.
//  Copyright © 2017年 AaronWei. All rights reserved.
//

import UIKit

class AWUserAccountViewModel: NSObject {
    
    static let sharedViewModel: AWUserAccountViewModel = AWUserAccountViewModel()
    
    var userAccount: AWUserAccountModel?
    
    var accessToken: String? {
        
        guard let token = userAccount?.access_token else { return nil }
        
        if userAccount?.expiresDate?.compare(Date()) == .orderedDescending {
            
            return token
            
        } else {
            
            return nil
            
        }
        
    }
    
    var isLogin: Bool {
        
        return accessToken != nil
        
    }
    
    override init() {
        
        super.init()
        
        userAccount = AWUserAccountModel.loadUserAccount()
        
    }
    
    func requestAccessToken(code: String, callBack:@escaping (Bool)->()) {
        
        AWNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            
            if error != nil {
                
                print(error!)
                
                callBack(false)
                
                return
                
            }
                
            let dict = response as! [String: Any]
                
            let userAccount = AWUserAccountModel(dict: dict)
                
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
            
        }
        
    }
    
    func requestUserInfo(userAccount: AWUserAccountModel, callBack:@escaping (Bool)->()) {
        
        AWNetworkTools.sharedTools.requestUserInfo(token: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
            
            if error != nil {
                
                print("网络请求异常: \(error!)")
                
                callBack(false)
                
                return
                
            }
                
            let dic = response as! [String: Any]
                
            let name = dic["name"] as? String
                
            let avatar_large = dic["avatar_large"] as? String
                
            userAccount.name = name
                
            userAccount.avatar_large = avatar_large
                
            userAccount.saveUserAccount()
            
            self.userAccount = userAccount
                
            callBack(true)
            
        }
    }

}
